using Unity.Burst;
using Unity.Entities;
using Unity.Mathematics;
using Unity.Transforms;

namespace HelloCube.Prefabs
{
    public partial struct FallAndDestroySystem : ISystem
    {
        [BurstCompile]
        public void OnCreate(ref SystemState state)
        {
            state.RequireForUpdate<Execute.Prefabs>();
        }

        [BurstCompile]
        public void OnUpdate(ref SystemState state)
        {
            float deltaTime = SystemAPI.Time.DeltaTime;
            foreach (var (transform, rotateSpeed) in SystemAPI.Query<RefRW<LocalTransform>, RefRO<RotateSpeed>>())
            {
                transform.ValueRW = transform.ValueRO.RotateY(rotateSpeed.ValueRO.RadiansPerSecond * deltaTime);
            }

            //使用 EntityCommandBufferSystem.Singleton 创建 ECB, 会在下一帧执行 played back 和 disposed
            var ecbSingleton = SystemAPI.GetSingleton<BeginSimulationEntityCommandBufferSystem.Singleton>();
            var ecb = ecbSingleton.CreateCommandBuffer(state.WorldUnmanaged);

            var movement = new float3(0, -deltaTime * 5f, 0);

            //WithAll 表示查询包含RotateSpeed组件的，但是不需要访问该组件
            //WithEntityAccess 将实体ID作为元组的最后一个元素
            foreach (var (transform, entity) in SystemAPI.Query<RefRW<LocalTransform>>().WithAll<RotateSpeed>()
                         .WithEntityAccess())
            {
                transform.ValueRW.Position += movement;
                if (transform.ValueRO.Position.y < 0)
                {
                    //删除会导致结构改变
                    //结构改变将使迭代查询无效
                    //所以使用ecb记录销毁实体的命令
                    ecb.DestroyEntity(entity);
                }
            }
        }
    }
}